<?php


namespace app\admin\controller;


use support\bootstrap\Redis;
use support\Db;
use support\Request;
use \Firebase\JWT\JWT;


class Login
{
    const key = 'liubao_auth#a1b2c3%@$321';
    public function index(Request $request)
    {
        if (Redis::get('auth_admin')) return json(json_decode(Redis::get('auth_admin'), true));
        Redis::set('auth_admin', json_encode(Db::table('auth_admin')->get()));
        return json(Db::table('auth_admin')->get());
    }

    public function login(Request $request)
    {
        $body = get_body($request);
        if (!$body) return json(['code' => '-1', 'message' => '参数不合规']);
        $result = Db::table('users')
            ->where([['name', '=', $body['username']], ['password', '=', md5(md5($body['password']))]])
            ->get();
        if (!(count($result) > 0)) return json(['code' => -1, 'msg' => '账号或密码错误']);
        $key = self::key;
        $payload = array(
            "iss" => $body['username'], // 签发者
            "aud" => "webman.liubao.org.cn",
            "iat" => time(), // 颁发时间
            "nbf" => time() + 60,
        );
        $jwt = JWT::encode($payload, $key);
        $session = $request->session();
        $session->set($body['username'], $jwt);
//        JWT::$leeway = 60; // $leeway in seconds
//        $decoded = JWT::decode($jwt, $key, array('HS256'));
//        print_r($decoded);
        return json(['code' => 0, 'message' => "Get token success", 'token' => $jwt, 'name' => $body['username']]);
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \support\Response
     */
    public function info(Request $request)
    {
        print_r($request);
        $token = $request->get('token');
        $body = get_body($request);
        print_r($body);
        if (!$token) return json(['code' => -1, 'message' => '登录失效']);
        $session = $request->session();
        $decoded = JWT::decode($token, self::key, array('HS256'));
        print_r($decoded);
        return json(['code' => 0, 'result' => ['name' => 'admin', 'avatar' => 22222]]);
//        if ($token === $session)

    }

    /**
     * 退出登录
     * @param Request $request
     * @return \support\Response
     */
    public function logout(Request $request)
    {
        $session = $request->session();
        $name = $request->cookie('name');
        if ($request->header('x-token') !== $session->get($name)) return json(['code' => -1, 'message' => 'logout error']); else {
            $session->forget($name);
            return json(['code' => 0, 'result' => 'success']);
        }
    }
}